using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using AutoStopData.Model;
using AutostopDataAccess.Domains;

namespace AutoStopData.Domains
{
    public partial class Regions : DomainBase<Region>
    {
        protected override Dictionary<String, Region> LoadFromDatabase()
        {
            var ret = new Dictionary<String, Region>();
            List<Region> databaseDomains;
            Debug.Write("Loading Regions.");
            using (var ctx = new AutoStopContext())
            {
                databaseDomains = ctx.Regions.Include(o => o.LocalizableResource.LocalizedResources).ToList();
            }
            foreach (var databaseDomain in databaseDomains)
            {
                String key = databaseDomain.RegionCode;
                ret.Add(key, databaseDomain);
            }
            Debug.Write("Regions loaded.");
            return ret;
        }

        public static List<RegionLocalized> All()
        {
            var instance = new Regions();
            Dictionary<string, Region> allDomains = instance.CurrentData();
            var retVal = new List<RegionLocalized>();
            if (allDomains.Count > 0)
            {
                retVal.AddRange(allDomains.Select(o => new RegionLocalized(o.Value)).OrderBy(ol => ol.LocalizedName));
            }
            return retVal;
        }

        public static List<RegionLocalized> AllWithBlank()
        {
            var retVal = new List<RegionLocalized> { new RegionLocalized() };
            retVal.AddRange(All());
            return retVal;
        }

        public static string GetNameByCode(String regionCode)
        {
            var instance = new Regions();
            Dictionary<string, Region> allDomains = instance.CurrentData();
            string retVal = All().Where(o => o.RegionCode == regionCode).First().LocalizedName;
            return retVal;
        }
    }

    #region Inner Class

    public class RegionLocalized
    {
        public string RegionCode { get; set; }
        public string CountryCode { get; set; }
        public string LocalizedName { get; set; }

        public RegionLocalized() { }

        public RegionLocalized(Region domain)
        {
            RegionCode = domain.RegionCode;
            CountryCode = domain.CountryCode;
            LocalizedName = GetLocalizedData(domain);
        }

        private static String GetLocalizedData(Region domain)
        {
            String retVal = domain.LocalizableResource.DefaultResourceName;
            const string language = "sk";
            var localizedResource = domain.LocalizableResource.LocalizedResources.FirstOrDefault(lr => lr.CultureCode == language);
            if (localizedResource != null)
            {
                retVal = localizedResource.ResourceName;
            }
            return retVal;
        }
    }

    #endregion
}